package com.gupao.rpc;

import com.gupao.rpc.discovery.IServiceDiscovery;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class RemoteInvocationHander implements InvocationHandler {

    private IServiceDiscovery serviceDiscovery;

    private String version;

    public RemoteInvocationHander(IServiceDiscovery serviceDiscovery,String version) {
        this.serviceDiscovery = serviceDiscovery;
        this.version = version;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //这里不走通常的代理逻辑，不执行method.invoke(),而是通过远程调用服务，相当于远程代理
        RpcRequest request = new RpcRequest();
        request.setServiceName(method.getDeclaringClass().getName());
        request.setMethodName(method.getName());
        request.setParameters(args);
        request.setVersion(version);
        String serviceName = request.getServiceName();
        String serviceAddress = serviceDiscovery.discoveryService(serviceName);
        TCPTransport tcpTransport = new TCPTransport(serviceAddress);
        return tcpTransport.send(request);
    }
}
